package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.entity.*;
import com.ruan.mapper.*;
import com.ruan.service.SkuService;
import com.ruan.utils.OssUtil;
import com.ruan.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;

/**
* @author 59499
* @description 针对表【sku】的数据库操作Service实现
* @createDate 2023-09-11 13:18:58
*/
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku>
    implements SkuService{

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private AttrValueMapper attrValueMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SpecKeyMapper specKeyMapper;

    @Autowired
    private SpecValueMapper specValueMapper;

    @Autowired
    private SpecOptionsMapper specOptionsMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public R<String> uploadEventsPicture(MultipartFile file) {
        //获取上传的文件名
        String fileName = file.getOriginalFilename();
        //产生新的文件名，时间戳+原先文件名后缀
        String newFileName = null;
        if (fileName != null) {
            newFileName = System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf('.'));
        }
        String path = "skupicture/";
        String url = null;
        if (newFileName != null) {
            try{
                url = OssUtil.upload(newFileName, file.getInputStream(),path);
            }catch (Exception e){
                return new R<>(100,"上传失败");
            }
        }
        return new R<>(200,"上传成功",url);
    }

    @Override
    @Transactional
    public R<Void> addSpuSku(Integer categoryId, List<AttrValue> attrValueList, List<Sku> skuList, Spu spu) {
        if (spu.getName() == null || Objects.equals(spu.getName(), "")){
            return new R<>(100,"商品名不能为空");
        }
        spu.setCategoryId(categoryId);
        int stock = 0;
        BigDecimal price = BigDecimal.valueOf(10000000);
        for (Sku sku:skuList){
            stock+= sku.getStock();
            int result = sku.getPrice().compareTo(price);

            if (result < 0) {
                price = sku.getPrice();
            }
        }
        spu.setStock(stock);
        spu.setPrice(price);
        int row = spuMapper.insert(spu);
        if (row != 1){
            return new R<>(100,"添加Spu失败");
        }


        int i=0;
        StringBuilder spuNamePart= new StringBuilder();
        for (AttrValue attrValue:attrValueList){
            attrValue.setSpuId(spu.getId());
            if (i==1){
                spuNamePart.append(spu.getName());
            }
            spuNamePart.append(attrValue.getValue());
            int row1 = attrValueMapper.insert(attrValue);
            if (row1 != 1){
                return new R<>(100,"添加AttrValue失败");
            }
            i++;
        }
        spu.setName(String.valueOf(spuNamePart));
        spuMapper.updateById(spu);

        Map<String, String> map = new HashMap<>();
        for (Sku sku:skuList){
            String[] pairs = sku.getProperties().split(";");
            StringBuilder ids = new StringBuilder(); // 用于拼接SpecOptions的id
            for (String pair : pairs) {
                String[] keyValue = pair.split(":");
                String key = keyValue[0];
                String value = keyValue[1];
                if ("price".equals(key)) {
                    break; // 如果键是"price"，则退出循环
                }

                QueryWrapper<SpecKey> wrapper = new QueryWrapper<>();
                wrapper.eq("title",key);
                wrapper.eq("category_id",categoryId);
                wrapper.eq("status",1);
                SpecKey specKey = specKeyMapper.selectOne(wrapper);
                QueryWrapper<SpecOptions> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("title",value);
                wrapper1.eq("spec_key_id",specKey.getId());
                wrapper1.eq("status",1);
                SpecOptions specOptions = specOptionsMapper.selectOne(wrapper1);
                if (specOptions != null) {
                    ids.append(specOptions.getId()).append("-");
                }


                // 检查map中是否存在该key
                if (!map.containsKey(key)) {
                    map.put(key, value);
                } else {
                    String existingValue = map.get(key);

                    // 将原有的value和新的value用逗号拼接
                    String[] values = existingValue.split(",");
                    if (!Arrays.asList(values).contains(value)) {
                        existingValue += "," + value;
                        map.put(key, existingValue);
                    }
                }

            }
            // 去除最后一个"-"
            if (ids.length() > 0) {
                ids.deleteCharAt(ids.length() - 1);
            }
            String properties = sku.getProperties();
            String[] splitStr = properties.split(";price");
            String result = splitStr[0];
            sku.setProperties(result);
            sku.setIds(String.valueOf(ids));
            sku.setSpuId(spu.getId());
            sku.setName(spu.getName()+sku.getName());
            int row2 = skuMapper.insert(sku);
            if (row2 != 1){
                return new R<>(100,"添加Sku失败");
            }
        }
        // 遍历map中的键值对
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            QueryWrapper<SpecKey> wrapper = new QueryWrapper<>();
            wrapper.eq("title",key);
            wrapper.eq("category_id",categoryId);
            wrapper.eq("status",1);
            SpecKey specKey = specKeyMapper.selectOne(wrapper);
            SpecValue specValue = new SpecValue();
            specValue.setSpecKeyId(specKey.getId());
            specValue.setValue(value);
            specValue.setSpuId(spu.getId());
            int row3 = specValueMapper.insert(specValue);
            if (row3 != 1){
                return new R<>(100,"添加SpecValue失败");
            }
        }

        return new R<>(200,"添加成功");
    }

    @Override
    public R<List<Sku>> getSkuBySpuId(Integer spuId) {
        List<Sku> skuList = redisCache.getCacheList("getSkuBySpuId"+spuId);
        if (!skuList.isEmpty()){
            return new R<>(200,"查询成功",skuList);
        }
        QueryWrapper<Sku> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id",spuId);
        wrapper.eq("status",1);
        List<Sku> skuList1 = skuMapper.selectList(wrapper);
        redisCache.setCacheList("getSkuBySpuId"+spuId,skuList1);
        return new R<>(200,"查询成功",skuList1);
    }

    @Override
    public R<Void> editSku(Sku sku) {
        Sku sku1 = skuMapper.selectById(sku.getId());
        if (sku1.equals(sku)){
            return new R<>(100,"不可修改相同规格");
        }
        sku.setUpdateTime(null);
        int row = skuMapper.updateById(sku);
        if (row != 1){
            return new R<>(100,"修改失败");
        }
        redisCache.deleteObject("getSkuBySpuId"+sku.getSpuId());
        redisCache.deleteObject("skuStock"+sku.getId());
        return new R<>(200,"修改成功");
    }

    @Override
    public R<List<Sku>> getAllSkuBySpuId(Integer spuId) {
        QueryWrapper<Sku> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id",spuId);
        List<Sku> skuList1 = skuMapper.selectList(wrapper);
        return new R<>(200,"查询成功",skuList1);
    }
}


